<template>
  <div class="main">
    <a-form
      :model="formData"
      class="user-layout-login"
      ref="formLogin"
      @submit="handleSubmit"
    >
      <!-- 错误提示信息 -->
      <a-alert
        v-if="showLoginErrorInfo"
        type="error"
        showIcon
        style="margin-bottom: 24px"
        :message="showLoginErrorInfo"
      />

      <a-form-item>
        <a-input
          @focus="usernameIcon = require('@/assets/svg/select-user.svg')"
          @blur="usernameIcon = require('@/assets/svg/user.svg')"
          size="large"
          type="text"
          placeholder="请输入账户"
          :rules="[{ required: true, message: '请输入帐户名' }]"
          validate-trigger="change"
          v-model:value="formData.username"
        >
          <template v-slot:prefix>
            <img src="@/assets/svg/user.svg" class="user" alt="user" />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item>
        <a-input-password
          @focus="passwordIcon = require('@/assets/svg/select-lock.svg')"
          @blur="passwordIcon = require('@/assets/svg/lock.svg')"
          size="large"
          placeholder="请输入密码"
          :rules=" [{ required: true, message: '请输入密码' }]"
          validate-trigger="change"
          v-model:value="formData.password"
        >
          <!-- <a-icon src="../../assets/svg/user.svg" alt=""> -->
          <template v-slot:prefix>
            <img src="@/assets/svg/lock.svg" class="user" alt="user" />
          </template>
        </a-input-password>
      </a-form-item>

      <div class="code">
        <a-form-item>
          <a-input
            @focus="vercodeIcon = require('@/assets/svg/select-code.svg')"
            @blur="vercodeIcon = require('@/assets/svg/code.svg')"
            class="code-input"
            size="large"
            type="text"
            placeholder="请输入人机验证码"
            :rules="[{ required: true, message: '请输入人机验证码' }]"
            validate-trigger="blur"
            v-model:value="formData.vercode"
          >
            <template v-slot:prefix>
              <img src="@/assets/svg/code.svg" class="user" alt="user" />
            </template>
          </a-input>
        </a-form-item>
        <div class="code-img" style="position: relative; background: #ddd">
          <img
            v-show="vercodeImgSrc"
            :src="vercodeImgSrc"
            @click="refVercode()"
          />
          <div class="vercode-mask" v-show="isOverdue" @click="refVercode()">
            已过期 请刷新
          </div>
        </div>
      </div>

      <a-form-item>
        <!-- 自动登录 -->
        <!-- <a-checkbox v-decorator="['rememberMe', { valuePropName: 'checked' }]">自动登录</a-checkbox> -->
        <a-checkbox v-model:checked="isAutoLogin">自动登录</a-checkbox>
        <!-- 忘记密码 -->
        <a class="forge-password" style="float: right">忘记密码?</a>
      </a-form-item>

      <a-form-item class="submit">
        <a-button
          size="large"
          type="primary"
          htmlType="submit"
          class="login-button"
          :loading="loginBtnLoadingFlag"
        >登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { useStore} from 'vuex'
import { timeFix } from '@/utils/util'
import { vercode, login } from '@/api/login'
import { Form } from 'ant-design-vue'
import { onMounted, ref, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'

const store = useStore();
const comp = getCurrentInstance()
const router = useRouter()
const useForm = Form.useForm

const formData = ref({
  username: '',
  password: '',
  vercode: ''
})
const formLogin = ref()
const isOverdue = ref(false)
const isAutoLogin = ref(true)
const loginBtnLoadingFlag = ref(false)
const showLoginErrorInfo = ref('')
const usernameIcon = ref(require('@/assets/svg/user.svg'))
const passwordIcon = ref(require('@/assets/svg/lock.svg'))
const vercodeIcon = ref(require('@/assets/svg/code.svg'))
const vercodeImgSrc = ref('')
const vercodeToken = ref('')
const timer = ref(null)

const onChange = (e) => {
  isAutoLogin.value = !isAutoLogin.value
}

const refVercode = () => {
  // 刷新图片验证码
  const that = this
  // 获取图形验证码
  vercode().then((res) => {
    vercodeImgSrc.value = res.imageBase64Data
    vercodeToken.value = res.vercodeToken
    isOverdue.value = false
    timer.value && clearInterval(timer.value) // 如果多次点击则清除已有的定时器
    // 超过60秒提示过期刷新
    timer.value = setInterval(() => {
      res.expireTime--
      if (res.expireTime <= 0) {
        isOverdue.value = true
        clearInterval(timer.value)
      }
    }, 1000)
  })
}

const loginSuccess = (res) => {
  // this.$router.push({ path: '/' })
  // 通过这里的传参 来得知是否点击自动登录按钮
  router.push({ path: '/', query: { isAutoLogin: isAutoLogin.value } })
  // 延迟 1 秒显示欢迎信息
  setTimeout(() => {
    // eslint-disable-next-line no-unused-expressions
    comp.appContext?.config?.globalProperties?.$notification.success({
      message: '欢迎',
      description: `${timeFix()}，欢迎回来`
    })
  }, 1000)
  showLoginErrorInfo.value = ''
}

const handleSubmit = (e) => {
  console.log('....................', formLogin.value)
  const that = this
  console.log('验证通过', formData.value)
  const values = formData.value
  let loginParams = { username: '', password: '', vercode: '', vercodeToken: '' }
  loginParams.username = values.username
  loginParams.password = values.password
  loginParams.vercode = values.vercode
  loginParams.vercodeToken = vercodeToken.value
  loginBtnLoadingFlag.value = true // 登录按钮显示加载loading
  store.dispatch('Login', {
    loginParams: loginParams,
    isSaveStorage: isAutoLogin
  })
      .then((res) => loginSuccess(res))
      .catch((err) => {
        showLoginErrorInfo.value = err.msg || JSON.stringify(err)
        loginBtnLoadingFlag.value = false
      })

  // formLogin.value && formLogin.value.validate().then(() => {
  //
  // }).catch(() => {
  //   console.log('验证失败')
  // })
}

onMounted(() => {
  refVercode()
})

</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .forge-password {
    font-size: 14px;
    color: @jee-theme;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
  .code {
    display: flex;
    justify-content: space-between;
    .code-input {
      width: 216px;
    }
    .code-img {
      width: 137px;
      height: 40px;
      background-color: #ddd;
      img {
        width: 137px;
        height: 40px;
      }
    }
  }
  .submit {
    margin-top: 50px;
  }
}
.vercode-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.8;
  text-align: center;
  line-height: 40px;
  color: #fff;
  &:hover {
    cursor: pointer;
  }
}
</style>
